package service

import (
	"gorm.io/gorm"
	"strconv"
	"zk2/internal/dao"
	"zk2/internal/dto"
	"zk2/internal/models"
	"zk2/pkg"
)

type UserServiceImpl interface {
	Register(req dto.RegisterReq) (resp *dto.RegisterResp, err error)
	Login(req dto.LoginReq) (resp *dto.LoginResp, err error)
}
type UserService struct {
	md5 *pkg.Md5
}

func NewUserService() *UserService {
	return &UserService{
		pkg.NewMd5(),
	}
}
func (u *UserService) Register(req dto.RegisterReq) (resp *dto.RegisterResp, err error) {
	userDao := dao.NewUserDao()
	data, _ := userDao.FindUserByMobile(req)
	if data.ID == 0 {
		user := &models.User{
			Model:    gorm.Model{},
			Mobile:   req.Mobile,
			Password: u.md5.Md5Str(req.Password),
		}
		err = userDao.UserAdd(user)
		if err != nil {
			return
		}
	}
	handler, err := pkg.NewJwt().TokenHandler(strconv.Itoa(int(data.ID)))
	if err != nil {
		return
	}
	return &dto.RegisterResp{
		Token: handler,
	}, nil
}
func (u *UserService) Login(req dto.LoginReq) (resp *dto.LoginResp, err error) {
	userDao := dao.NewUserDao()
	req.Password = u.md5.Md5Str(req.Password)
	login, err := userDao.Login(req)
	if err != nil {
		return nil, err
	}
	handler, err := pkg.NewJwt().TokenHandler(strconv.Itoa(int(login.ID)))
	if err != nil {
		return nil, err
	}
	return &dto.LoginResp{Token: handler}, nil
}
